/*
 * Copyright 1999-2101 Alibaba Group.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.fastjson.serializer;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 
 * @author wenshao<szujobs@hotmail.com>
 * 
 */
public abstract class FieldSerializer {
	protected final String name;
	private final Method method;
	private final String double_quoted_fieldPrefix;
	private final String single_quoted_fieldPrefix;
	private final String un_quoted_fieldPrefix;

	public FieldSerializer(String name, Method method) {
		super();
		this.name = name;
		this.method = method;
		method.setAccessible(true);

		this.double_quoted_fieldPrefix = '"' + name + "\":";

		this.single_quoted_fieldPrefix = '\'' + name + "\':";

		this.un_quoted_fieldPrefix = name + ":";
	}

	public String getName() {
		return name;
	}

	public Method getMethod() {
		return method;
	}

	public void writePrefix(JSONSerializer serializer) throws IOException {
		SerializeWriter out = serializer.getWrier();
		
		if (serializer.isEnabled(SerializerFeature.QuoteFieldNames)) {
			if (serializer.isEnabled(SerializerFeature.UseSingleQuotes)) {
				out.write(single_quoted_fieldPrefix);
			} else {
				out.write(double_quoted_fieldPrefix);
			}
		} else {
			out.write(un_quoted_fieldPrefix);
		}
	}
	
	public Object getPropertyValue(Object object) throws Exception {
		return method.invoke(object);
	}

	public abstract void writeProperty(JSONSerializer serializer, Object propertyValue) throws Exception;

}